<template>
	<view class="">
		<u-form :model="form" ref="uForm" :errorType="errorType">
			<view>
				<view class="formBox">
					<view class="title">基础信息</view>
					<u-form-item label-width="150rpx" label="活动标题" prop="collectName" required>
						<u-input input-align="right" placeholder="请输入活动标题" v-model="form.collectName" />
					</u-form-item>
					<u-form-item label-width="200rpx" label="活动开始时间" prop="timeStart" required>
						<u-input input-align="right" v-model="form.timeStart" placeholder="请选择时间" disabled
							@click="openTimeShow('timeStart')" />
					</u-form-item>
					<u-form-item label-width="200rpx" label="活动结束时间" prop="timeEnd" required>
						<u-input input-align="right" v-model="form.timeEnd" placeholder="请选择时间" disabled
							@click="openTimeShow('timeEnd')" />
					</u-form-item>
					<u-form-item label-width="200rpx" label="虚拟参加人数" prop="inventedEnrollNumber	">
						<u-input input-align="right" type="digit" placeholder="请输入虚拟参加人数"
							v-model="form.inventedEnrollNumber" />
					</u-form-item>
					<u-form-item label-width="200rpx" label="活动地点" prop="collectType" required>
						<u-radio-group v-model="form.collectType">
							<u-radio size="50" @change="e => radioChange(item.value, 'collectType')"
								v-for="(item, index) in isList" :key="index" :name="item.value"
								:disabled="item.disabled">
								{{ item.name }}
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label-width="150rpx" label="活动门店" prop="joinStores" required
						v-if="form.collectType == 1">
						<u-input input-align="right" placeholder="请输入活动标题" v-show="false" v-model="form.joinStores" />
						<view style="width: 100%;" @click="goselectStore"
							v-if="form.joinStores.split(',').length && form.joinStores.length != 0 && selectStore.length == 0">
							已选择{{ form.joinStores.split(',').length }}家门店
						</view>
						<view style="width: 100%;" @click="goselectStore" v-else-if="selectStore.length != 0">
							已选择{{ selectStore.length }}家门店</view>
						<view style="width: 100%;" @click="goselectStore" v-else>请选择门店</view>
					</u-form-item>
					<u-form-item label-width="150rpx" label="外展地点" prop="latitude" required
						v-if="form.collectType == 2">
						<u-input input-align="right" placeholder="请输入活动标题" v-show="false" v-model="form.latitude" />
						<view style="width: 100%;" @click="selectLoction" v-if="!form.latitude">请选择地址</view>
						<view style="width: 100%;" @click="selectLoction" v-else>{{ form.address }}</view>
					</u-form-item>
					<u-form-item label-width="200rpx" label="支付设置" prop="isPay" required>
						<u-radio-group v-model="form.isPay">
							<u-radio size="50" @change="e => radioChange(item.value, 'isPay')"
								v-for="(item, index) in isPayList" :key="index" :name="item.value"
								:disabled="item.disabled">
								{{ item.name }}
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label-width="200rpx" label="报名订金" prop="deposit" required v-if="form.isPay == 1">
						<u-input input-align="right" type="digit" placeholder="请输入金额/元" v-model="form.deposit" />
					</u-form-item>
					<u-form-item label-width="200rpx" label="支付奖励积分" prop="bonusPointsType" required
						v-if="form.isPay == 1">
						<u-radio-group v-model="form.bonusPointsType">
							<u-radio size="50" @change="e => radioChange(item.value, 'bonusPointsType')"
								v-for="(item, index) in isAwardList" :key="index" :name="item.value"
								:disabled="item.disabled">
								{{ item.name }}
							</u-radio>
						</u-radio-group>
					</u-form-item>
				</view>
				<view class="formBox">
					<view class="title">活动信息</view>
					<u-form-item label-position="top" label-width="200rpx" label="活动封面" prop="coverImage" required>
						<view class="remark">支持格式jpg/png，宽高比为4:3，仅限一张图片</view>
						<u-upload :max-size="5 * 1024 * 1024" width="160" :auto-upload="true" :action="action"
							name="files" :file-list="fileList" @on-success="onSuccess" @on-list-change="onListChange"
							max-count="1" :show-progress="false" height="160"></u-upload>
					</u-form-item>
					<u-form-item label-position="top" label-width="200rpx" label="详情封面" prop="detailsImage" required>
						<view class="remark">支持格式jpg/png，宽高比为5:2，仅限一张图片</view>
						<u-upload :max-size="5 * 1024 * 1024" width="160" :auto-upload="true" :action="action"
							name="files" :file-list="fileList1" @on-success="onSuccess1" @on-list-change="onListChange1"
							max-count="1" :show-progress="false" height="160"></u-upload>
					</u-form-item>
					<u-form-item label-position="top" label-width="150rpx" label="分享封面" prop="shareImage" required>
						<view class="remark">支持格式jpg/png，宽高比为5:4，仅限一张图片</view>
						<u-upload :max-size="5 * 1024 * 1024" width="160" :auto-upload="true" :action="action"
							name="files" :file-list="fileList2" @on-success="onSuccess2" @on-list-change="onListChange2"
							max-count="1" :show-progress="false" height="160"></u-upload>
					</u-form-item>
					<u-form-item label-width="150" label="活动内容" prop="collectContent" required>
						<view style="width: 100%;" @click="goShopDetail">{{
                form.collectContent.length > 0 ? '修改活动内容' : '请输入活动内容'
              }}
						</view>
						<!-- <u-input input-align="right"  placeholder="请输入商品详情" disabled v-model="model.details" @click="goShopDetail" type="text"></u-input> -->
					</u-form-item>
				</view>
			</view>
		</u-form>
		<view class="f-c-fe">
			<view class="privew" @click="submit(2)">预览效果</view>
		</view>
		<view class="lxdBtn" @click="submit(1)">保存</view>
		<u-toast ref="uToast" />
		<u-picker mode="time" placeholder="请选择时间" @confirm="selectTime" v-model="timeShow" :params="params"></u-picker>
		<u-action-sheet :list="typeList" v-model="typeListShow" @click="actionSheetCallback"></u-action-sheet>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import {
		dateFormat
	} from '@/utils/common/dateTime';
	import {
		collectDetail,
		collectEdit,
		collectScore
	} from '@/api/marketing';

	export default {
		data() {
			return {
				id: '',
				errorType: ['message'],
				score: 0,
				fileList1: [],
				fileList2: [],
				fileList: [],
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false,
					timestamp: true
				},
				show: false,
				timeShow: false,
				typeListShow: false,
				stepStatus: false,
				action: 'https://sj.shopec.com.cn/hty-manage-api/upload/files',
				form: {
					collectName: '',
					timeStart: '',
					timeEnd: '',
					inventedEnrollNumber: '',
					joinStores: '',
					collectType: '1',
					address: '',
					longitude: '',
					latitude: '',
					isPay: '1',
					deposit: '',
					coverImage: '',
					bonusPoints: '',
					bonusPointsType: '1',
					shareImage: '',
					detailImage: '',
					collectContent: ''
				},
				seckillGsDtos: [],
				isList: [{
						name: '门店',
						value: 1,
						disabled: false
					},
					{
						name: '外展',
						value: 2,
						disabled: false
					}
				],
				isPayList: [{
						name: '是',
						value: 1,
						disabled: false
					},
					{
						name: '否',
						value: 2,
						disabled: false
					}
				],
				isAwardList: [{
						name: '无',
						value: 1,
						disabled: false
					},
					{
						name: '奖励积分',
						value: 2,
						disabled: false
					}
				],
				rules: {
					collectName: [{
						required: true,
						message: '请输入',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}],
					timeStart: [{
						required: true,
						message: '请选择时间',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}],
					timeEnd: [{
						required: true,
						message: '请选择时间',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}],
					inventedEnrollNumber: [{
						message: '请输入数字',
						type: 'number',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}],
					collectContent: [{
						required: true,
						message: '请输入',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}],
					joinStores: [{
						validator: (rule, value, callback) => {
							console.log(value);
							if (String(value).length == 0 && this.form.collectType == 1) {
								return false;
							} else {
								callback();
							}
						},
						message: '请选择门店',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}],
					latitude: [{
						validator: (rule, value, callback) => {
							console.log(value);
							if (String(value).length == 0 && this.form.collectType == 2) {
								return false;
							} else {
								callback();
							}
							return value.length !== 0;
						},
						message: '请选择外展地点',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['change', 'blur']
					}],
					deposit: [{
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							return this.$u.test.amount(value);
						},
						message: '金额格式不正确',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur']
					}]
				}
			};
		},
		computed: {
			...mapGetters(['userInfo', 'selectStore', 'selectStaff'])
		},
		onLoad(option) {
			this.id = JSON.parse(option.param).id;
			this.getDetail();
			this.getcollectScore();
		},
		onShow() {
			if (this.$get('addHtml')) {
				this.form.collectContent = this.$get('addHtml');
			}
		},
		onUnload() {
			this.$remove('addHtml');
			this.$remove('seckillDetail');
			this.$store.commit('setSelectStaff', []);
			this.$store.commit('setSelectStore', []);
		},
		methods: {
			getDetail() {
				collectDetail({
					id: this.id
				}).then(res => {
					this.form = res.data;
					var urlObj = {
						url: '',
						error: false, // 上传失败，此值为true
						progress: 100 // 0-100之间的值
					};
					urlObj.url = this.$imagePath + res.data.coverImage;
					this.fileList.push(urlObj);
					var urlObj1 = {
						url: '',
						error: false, // 上传失败，此值为true
						progress: 100 // 0-100之间的值
					};
					urlObj1.url = this.$imagePath + res.data.detailImage;
					this.fileList1.push(urlObj1);
					var urlObj2 = {
						url: '',
						error: false, // 上传失败，此值为true
						progress: 100 // 0-100之间的值
					};
					urlObj2.url = this.$imagePath + res.data.shareImage;
					this.fileList2.push(urlObj2);

					if (res.data.bonusPoints != 0) {
						this.form.bonusPointsType = 2;
					} else {
						this.form.bonusPointsType = 1;
					}
				});
			},
			onListChange(lists, index) {
				this.fileList = lists;
			},
			onListChange1(lists, index) {
				this.fileList1 = lists;
			},
			onListChange2(lists, index) {
				this.fileList2 = lists;
			},
			getcollectScore() {
				collectScore().then(res => {
					this.isAwardList[1].name = `奖励${res.data.score}积分`;
					this.score = res.data.score;
				});
			},
			addShop(type, index) {
				this.show = true;
				this.editStatus = type;
				this.editStatusIndex = index;
				if (type == 2) {
					this.shop = this.seckillGsDtos[index];
				} else {
					this.shop = {
						goodsServerName: '',
						goodsServerPrice: '',
						goodsServerNumber: '',
						goodsServerDescribe: ''
					};
				}
			},
			radioChange(e, type) {
				console.log(e);
				this.form[type] = e;
			},
			onSuccess(data, index, lists, name) {
				console.log(data, index, lists, name);
				this.form.coverImage = data.data.saveUrl;
			},
			onSuccess1(data, index, lists, name) {
				console.log(data, index, lists, name);
				this.form.detailImage = data.data.saveUrl;
			},
			onSuccess2(data, index, lists, name) {
				console.log(data, index, lists, name);
				this.form.shareImage = data.data.saveUrl;
			},
			submit(type) {
				if (this.form.collectType == 1 && this.selectStore.length > 0) {
					var str = '';
					this.selectStore.forEach((val, index) => {
						if (index == this.selectStore.length - 1) {
							str = str + val.storeId;
						} else {
							str = str + val.storeId + ',';
						}
					});
					this.form.joinStores = str;

					delete this.form.latitude;
					delete this.form.longitude;
				} else if (this.form.collectType == 2) {
					delete this.form.joinStores;
				}
				if (this.form.isPay == 2) {
					delete this.form.deposit;
					delete this.form.bonusPoints;
				} else {
					if (this.form.bonusPointsType == 1) {
						this.form.bonusPoints = 0;
					} else {
						this.form.bonusPoints = this.score;
					}
				}

				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过');
						var data = {
							...this.form,
							storeBasicId: this.userInfo.storeBasicId
						};

						if (data.coverImage.length == 0) {
							this.$refs.uToast.show({
								title: '请上传活动封面图片',
								type: 'error'
							});
							return;
						}
						if (data.detailImage.length == 0) {
							this.$refs.uToast.show({
								title: '请上传活动详情图片',
								type: 'error'
							});
							return;
						}
						if (data.shareImage.length == 0) {
							this.$refs.uToast.show({
								title: '请上传分享封面图片',
								type: 'error'
							});
							return;
						}
						data.collectContent = encodeURI(data.collectContent);
						this.$put('collectDetail', data);
						if (type == 2) {
							this.$navigateTo('./preview', {});
							return;
						}
						collectEdit(data).then(res => {
							if (res.code == 1) {
								this.$put('isCreatStatus', '1');
								uni.switchTab({
									url: '/pages/marketing/marketing'
								});
							} else {
								this.$refs.uToast.show({
									title: res.msg,
									type: 'error'
								});
							}
						});
					} else {
						console.log('验证失败');
					}
				});
			},
			goselectStore() {
				this.$store.commit('setSelectStoreStr', this.form.joinStores);
				this.$navigateTo('/pages/selectStore/selectStore', {});
			},
			goShopDetail() {
				this.$put('addHtml', this.form.collectContent);
				this.$navigateTo('/workbench/shopDetail/shopDetail', {});
			},
			openSelect(type) {
				this.selectType = type;
				this.typeListShow = true;
			},
			openTimeShow(type) {
				this.timeType = type;
				this.timeShow = true;
			},
			selectTime(e) {
				console.log(e);
				if (this.timeType == 'timeEnd' && this.form.timeStart.length == 0) {
					this.$refs.uToast.show({
						title: '请选择开始时间',
						type: 'error'
					});
					return;
				} else if (this.timeType == 'timeEnd' && this.form.timeStart.length != 0) {
					var date = new Date(this.form.timeStart);
					if ((e.timestamp + 600) * 1000 < date.getTime()) {
						this.$refs.uToast.show({
							title: '结束时间不能小于开始时间',
							type: 'error'
						});
						return;
					}
				}
				if ((e.timestamp + 600) * 1000 < +new Date()) {
					this.$refs.uToast.show({
						title: '时间不能小于当前时间',
						type: 'error'
					});
					return;
				}
				this.form[this.timeType] = dateFormat(e.timestamp, 'yyyy-MM-dd');
			},
			// 点击actionSheet回调
			actionSheetCallback(index) {
				console.log(index);
				var key = this.selectType + 'Str';
				this.form[this.selectType] = this.typeList[index].value;
				this.form[key] = this.typeList[index].text;
			},
			selectLoction() {
				const that = this;
				uni.chooseLocation({
					success: function(res) {
						that.form.latitude = res.latitude;
						that.form.address = res.address;
						that.form.longitude = res.longitude;
					}
				});
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	};
</script>
<style lang="less" scoped>
	.formBox-wrapper {
		height: 70vh;
		padding-top: 50rpx;
	}

	.list:nth-last-child(1) {
		border: 0;
	}

	.list {
		border-bottom: 1px solid #ccc;
		width: 100%;
		padding-bottom: 40rpx;

		.name {
			font-size: 28rpx;
			font-weight: 700;
			text-align: left;
			color: #131313;
			line-height: 36px;
		}

		.info {
			line-height: 50rpx;

			.label {
				width: 50%;
				line-height: 80rpx;
			}
		}
	}

	.lastStep {
		width: 320rpx;
		height: 100rpx;
		opacity: 1;
		border: 2px solid #177fff;
		border-radius: 13rpx;
		font-size: 32rpx;
		text-align: center;
		color: #177fff;
		line-height: 100rpx;
		font-weight: 700;
	}

	.f-c-sa {
		margin: 50rpx 0;

		.lxdBtn {
			width: 320rpx;
			height: 100rpx;
			margin: 0;
			border-radius: 13rpx;
		}
	}

	.privew {
		font-size: 32rpx;
		font-weight: bold;
		text-align: left;
		color: #177fff;
		line-height: 64rpx;
		border-bottom: 1px solid #177fff;
		margin: 20rpx 25rpx 70rpx;
	}

	.remark {
		font-size: 24rpx;
		color: #888888;
		line-height: 30rpx;
	}
</style>
